package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.utils.SnackbarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.Res;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.LpUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.PopLvAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建小组
 * Created by Administrator on 2019/3/26 0026.
 */

public class TeacherCreateGroupActivity extends BaseActivity {

    @BindView(R.id.ll_main)
    LinearLayout llMain;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.iv_user_headimg)
    RoundedImageView ivUserHeadimg;
    @BindView(R.id.rl_group_icon)
    RelativeLayout rlGroupIcon;
    @BindView(R.id.iv2)
    ImageView iv2;
    @BindView(R.id.et_user_chinese_name)
    TextView etUserChineseName;
    @BindView(R.id.rl_group_name)
    RelativeLayout rlGroupName;

    //Handler对象
    private Handler handler = new Handler();

    //已经使用的小组头像的集合
    private ArrayList<Integer> usedGroupIcons;

    //已经使用的小组的姓名
    private ArrayList<String> usedGroupNames;

    //可以使用头像的集合
    private List<Integer> icons;

    //记录可用的索引
    private List<Integer> index;

    private ImageView lvClose;
    private ImageView lvLeft;
    private ImageView lvRight;
    private ImageView lvTeam;
    private TextView tvSave;

    //小组头像的集合
    private int[] res = {R.drawable.teacher_team1, R.drawable.teacher_team2, R.drawable.teacher_team3, R.drawable.teacher_team4, R.drawable.teacher_team5,
            R.drawable.teacher_team6, R.drawable.teacher_team7, R.drawable.teacher_team8, R.drawable.teacher_team9, R.drawable.teacher_team10,};

    //切换图片的位置索引值
    private int pos = 0;

    //用于记录小组头像,上传给服务器的小组头像的值
    private int icon = -1;

    //用于记录创建的小组名称,上传给服务器
    private String name;

    //默认的弹框供选择的名称
    private List<String> names;

    //跳转的请求码
    private static final int REQUETCODE = 0x350;

    //小组所在的班级
    private String classNum;

    /**
     * 跳转到该界面的方法
     */
    public static void goActivity(Context context, ArrayList<Integer> usedGroupIcons, ArrayList<String> usedGroupNames, String classNum) {
        Intent it = new Intent(context, TeacherCreateGroupActivity.class);
        Bundle bundle = new Bundle();
        bundle.putIntegerArrayList("icons", usedGroupIcons);
        bundle.putStringArrayList("names", usedGroupNames);
        bundle.putString("num", classNum);
        it.putExtras(bundle);
        context.startActivity(it);
    }


    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_create_group;
    }

    @Override
    protected void init() {
        initStateBar();

        //获取传递的数据
        initIntent();

        //统计可以选择的头像
        initIcons();

        //设置编辑按钮
        initEdit();

        //初始化新小组的头像
        initGropIcon();
    }


    /**
     * 获取传递的数据
     */
    private void initIntent() {
        usedGroupIcons = getIntent().getIntegerArrayListExtra("icons");
        usedGroupNames = getIntent().getStringArrayListExtra("names");
        classNum = getIntent().getStringExtra("num");
    }


    /**
     * 统计可以选择的头像集合
     */
    private void initIcons() {
        icons = new ArrayList<>();
        index = new ArrayList<>();
        for (int i = 1; i < 11; i++) {
            //如果已经使用的头像icons不包含1-10的索引,则证明该索引位置上的头像是可以选择
            if (!usedGroupIcons.contains(i)) {
                icons.add(res[i - 1]);
                index.add(i);
            }
        }
    }


    /**
     * 设置保存按钮
     */
    private void initEdit() {
        lvEdit.setVisibility(View.VISIBLE);
        RelativeLayout.LayoutParams lp = LpUtils.getRelatLp(UiUtils.dp2px(64), UiUtils.dp2px(30));
        lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT | RelativeLayout.CENTER_VERTICAL);
        lvEdit.setLayoutParams(lp);
        lvEdit.setImageResource(R.drawable.img_create);
        tvTitle.setText("创建小组");
    }


    /**
     * 初始话新小组的头像,注意小组头像也还是不可编辑的
     */
    private void initGropIcon() {
        ivUserHeadimg.setImageResource(res[usedGroupIcons.size()]);
        icon = usedGroupIcons.size() + 1;
    }


    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.lv_edit, R.id.rl_group_icon, R.id.rl_group_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.lv_edit:
                //创建小组
                doCreateGroupAction();
                break;
            case R.id.rl_group_icon:
                //弹出选择小组头像
//                showChooseHeadPop();
                break;
            case R.id.rl_group_name:
                //选择名称
                showChooseNamePop();
                break;
        }
    }

    /**
     * 创建小组
     */
    private void doCreateGroupAction() {

        if (icon == -1) {
            //表示没有选择头像
            SnackbarUtil.ShortSnackbar(llMain, "请选择小组头像", 0).show();
            return;
        }

        if (TextUtils.isEmpty(name)) {
            //表示没有选择头像
            SnackbarUtil.ShortSnackbar(llMain, "请选择或创建小组名称", 0).show();
            return;
        }

        CustomDialogManager.show(this, "创建中...");

        Map<String, String> map = new HashMap<>();

        map.put("type", "5");
        map.put("userID", AccountUtils.getAccount(this));
        //小组头像
        map.put("icon", icon + "");

        //小组名称
        map.put("name", name);

        //班级
        map.put("classnum", classNum);

        //口号传空
        map.put("slogan", "");

        //目标传空
        map.put("taget", "");

        //音乐传空
        map.put("music", "");

        HttpUtils.post(HttpAddress.CREATETEAM, map, this, new HttpCallBack<Res>() {
            @Override
            public void onSuccess(Res res) {
                CustomDialogManager.dissmiss();
                if (1 == res.getState()) {
                    //创建成功
                    ToastUtils.showShort("创建小组成功" + res.getState());
                    //EventBus通知TeacherClassInfoActivity界面刷新
                    sendUpdateMsg();
                } else {
                    //创建失败
                    ToastUtils.showShort("创建小组失败,错误码是:" + res.getState());
                }

            }

            @Override
            public void onError(String e) {
                CustomDialogManager.dissmiss();
                ToastUtils.showShort(BaseApplication.ERROR);
            }
        });


    }

    /**
     * 弹出选择名称
     */
    private void showChooseNamePop() {
        names = new ArrayList<>();

        names.add("智者队");
        names.add("勇者队");
        names.add("欢乐队");
        names.add("博爱队");
        names.add("自定义");

        PopUpManager.showPop(this, R.layout.pop_commonview, 0.3f, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                ListView lvCommon = view.findViewById(R.id.lv);
                TextView tvCancel = view.findViewById(R.id.tv_cancel);
                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                    }
                });

                PopLvAdapter adapter = new PopLvAdapter(TeacherCreateGroupActivity.this, names, R.layout.lv_item_pop_common);
                lvCommon.setAdapter(adapter);
                lvCommon.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                        if (pos != names.size() - 1) {
                            //选择选项
                            if (!usedGroupNames.contains(names.get(pos))) {
                                name = names.get(pos);
                                etUserChineseName.setText(names.get(pos));
                            } else {
                                ToastUtils.showShort("小组名称已经被使用,请重新选择");
                            }

                        } else {
                            //选择自定义,跳转到自定义界面
                            Intent intent = new Intent(TeacherCreateGroupActivity.this, TeacherUpdataTeamInfoActivity.class);
                            intent.putExtra("type", TeacherUpdataTeamInfoActivity.TEAMCREATENAME);
                            intent.putStringArrayListExtra("usedname", usedGroupNames);
                            startActivityForResult(intent, REQUETCODE);
                        }

                        PopUpManager.dismiss();
                    }
                });
            }
        });
    }

    /**
     * 回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == REQUETCODE && resultCode == TeacherUpdataTeamInfoActivity.TEAMNEWNAME) {
            name = data.getStringExtra("data");
            etUserChineseName.setText(name);
        }
    }

    /**
     * 弹出选择小组头像
     */
    private void showChooseHeadPop() {
        PopUpManager.showPop(this, R.layout.pop_item_head, 0.3f, this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                lvClose = view.findViewById(R.id.lv_close);
                lvLeft = view.findViewById(R.id.lv_left);
                lvRight = view.findViewById(R.id.lv_right);
                lvTeam = view.findViewById(R.id.lv_team);
                tvSave = view.findViewById(R.id.tv_save);
                //初始状态将左边的箭头隐藏,右边的箭头显示
                lvLeft.setVisibility(View.INVISIBLE);
                lvRight.setVisibility(View.VISIBLE);
                lvTeam.setImageResource(icons.get(pos));

                lvClose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                        pos = 0;
                    }
                });

                lvLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        syncLeftState();
                    }
                });

                lvRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        syncRightState();
                    }
                });

                tvSave.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ivUserHeadimg.setImageResource(icons.get(pos));

                        //记录上传给服务器的icon
                        icon = index.get(pos);

                        //重置当前位置
                        pos = 0;

                        PopUpManager.dismiss();
                    }
                });
            }
        });
    }

    /**
     * 点击右箭头同步状态的方法
     */
    private void syncRightState() {
        pos++;
        if (lvLeft.getVisibility() != View.VISIBLE) {
            lvLeft.setVisibility(View.VISIBLE);
        }
        if (pos == icons.size()) {
            pos = icons.size();
            return;
        } else {
            lvRight.setVisibility(View.VISIBLE);
            if (pos == icons.size() - 1) {
                lvRight.setVisibility(View.INVISIBLE);
            }
            lvTeam.setImageResource(icons.get(pos));
        }
    }

    /**
     * 点击左箭头同步状态的方法
     */
    private void syncLeftState() {
        pos--;
        if (lvRight.getVisibility() != View.VISIBLE) {
            lvRight.setVisibility(View.VISIBLE);
        }

        if (pos < 0) {
            pos = 0;
            return;
        } else {
            lvLeft.setVisibility(View.VISIBLE);
            if (pos == 0) {
                lvLeft.setVisibility(View.INVISIBLE);
            }
            lvTeam.setImageResource(icons.get(pos));
        }
    }


    /**
     * 通知班级信息界面刷新的方法
     */
    private void sendUpdateMsg() {

        //通知TeacherClassInfoAcitivity界面刷新
        BusInfo busInfo = new BusInfo();
        busInfo.type = TeacherClassInfoActivity.CREATEGROUPSUCCESS;
        EventBus.getDefault().post(busInfo);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 600);
    }

    @Override
    protected void onDestroy() {
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }

}
